package com.sinosoft.taxbenefit.core.customer.biz.service.impl;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.ws.BindingProvider;
import javax.xml.ws.Holder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.sinosoft.platform.base.TaxBaseService;
import com.sinosoft.platform.common.config.SystemConstants;
import com.sinosoft.platform.common.exception.BusinessDataErrException;
import com.sinosoft.platform.common.util.DateUtil;
import com.sinosoft.platform.common.util.StringUtil;
import com.sinosoft.taxbenefit.api.base.EBResultCodeDTO;
import com.sinosoft.taxbenefit.api.base.HXResultCodeDTO;
import com.sinosoft.taxbenefit.api.config.ENUM_BZ_RESPONSE_RESULT;
import com.sinosoft.taxbenefit.api.config.ENUM_DISPOSE_TYPE;
import com.sinosoft.taxbenefit.api.config.ENUM_SENDSERVICE_CODE;
import com.sinosoft.taxbenefit.api.dto.request.TaxFaulTaskDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.CoreRequestHead;
import com.sinosoft.taxbenefit.api.dto.request.base.ParamHeadDTO;
import com.sinosoft.taxbenefit.api.dto.request.base.ThirdSendResponseDTO;
import com.sinosoft.taxbenefit.api.dto.request.customer.ReqCustomerCoreDTO;
import com.sinosoft.taxbenefit.api.dto.request.customer.ReqCustomerInfoDTO;
import com.sinosoft.taxbenefit.api.dto.request.customer.ReqCustomerMoreCoreDTO;
import com.sinosoft.taxbenefit.api.dto.request.customer.ReqCustomerMoreDTO;
import com.sinosoft.taxbenefit.api.dto.response.customer.CustomerVerifyResultDTO;
import com.sinosoft.taxbenefit.core.common.biz.service.CommonCodeService;
import com.sinosoft.taxbenefit.core.common.config.ENUM_EBAO_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_HX_SERVICE_PORT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RC_STATE;
import com.sinosoft.taxbenefit.core.common.config.ENUM_RESULT_CODE;
import com.sinosoft.taxbenefit.core.common.config.ENUUM_CODE_MAPPING;
import com.sinosoft.taxbenefit.core.common.dto.BookSequenceDTO;
import com.sinosoft.taxbenefit.core.common.dto.EbaoServerPortDTO;
import com.sinosoft.taxbenefit.core.common.dto.SendLogDTO;
import com.sinosoft.taxbenefit.core.common.dto.ThirdSendDTO;
import com.sinosoft.taxbenefit.core.customer.biz.service.CustomerServiceCore;
import com.sinosoft.taxbenefit.core.customer.config.CustomerConstants;
import com.sinosoft.taxbenefit.core.customer.dto.CustomerDTO;
import com.sinosoft.taxbenefit.core.customer.dto.CustomerVerifyDTO;
import com.sinosoft.taxbenefit.core.customer.dto.ReqCustomerVerifyDTO;
import com.sinosoft.taxbenefit.core.customer.dto.ResCustomerVerifyDTO;
import com.sinosoft.taxbenefit.core.ebaowebservice.AsynResultQueryService;
import com.sinosoft.taxbenefit.core.ebaowebservice.AsynResultQueryService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.CustomerVerifyService;
import com.sinosoft.taxbenefit.core.ebaowebservice.CustomerVerifyService_Service;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseBody;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseHeader;
import com.sinosoft.taxbenefit.core.ebaowebservice.ResponseJSON;
import com.sinosoft.taxbenefit.core.faultTask.biz.service.FaultTaskService;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxCustomerMapper;
import com.sinosoft.taxbenefit.core.generated.mapper.TaxFaultTaskMapper;
import com.sinosoft.taxbenefit.core.generated.model.TaxCustomer;
import com.sinosoft.taxbenefit.core.generated.model.TaxCustomerExample;
import com.sinosoft.taxbenefit.core.generated.model.TaxFaultTask;
import com.sinosoft.taxbenefit.core.transCode.biz.service.TransCodeService;
/**
 * 客户验证上传 
 * @author zhangyu
 * @date 2016年3月10日 上午9:39:57
 */
@Service
public class CustomerServiceCoreImpl extends TaxBaseService implements CustomerServiceCore {
	@Autowired
	private TaxCustomerMapper taxCustomerMapper;
	@Autowired
	private FaultTaskService faultTaskService;
	@Autowired
	TaxFaultTaskMapper  taxFaultTaskMapper;//异常任务
	@Autowired
	CommonCodeService commonCodeService;
	@Autowired
	TransCodeService transCodeService;
	
	@Override
	public ThirdSendResponseDTO addCustomer(ReqCustomerInfoDTO reqCustomerInfoDTO, ParamHeadDTO paramHead) {
		ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
		try {
			logger.info("单笔客户验证上传（核心请求）JSON 体数据内容："+JSONObject.toJSONString(reqCustomerInfoDTO));
			// 1.将客户验证请求dto转换为中保信客户验证请求dto
			ReqCustomerVerifyDTO  reqCustomerVerifyDTO = this.tansforDTO(reqCustomerInfoDTO);
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code(), paramHead,reqCustomerVerifyDTO);
			logger.info("客户验证上传（请求中保信）JSON 数据内容："+JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			CustomerVerifyService_Service service = new CustomerVerifyService_Service(wsdlLocation);
			CustomerVerifyService servicePort = service.getCustomerVerifyServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.verify(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("客户验证上传（中保信响应）JSON 数据内容："+responseBody.getJsonString());
			// 封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHead.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			// 3.封装返回核心dto;
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode()) 
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			// 获取业务数据
			if(!StringUtil.isEmpty(responseBody.getJsonString())){
				ResCustomerVerifyDTO resCustomerVerifyDTO = JSONObject.parseObject(responseBody.getJsonString(), ResCustomerVerifyDTO.class);
				if (null != resCustomerVerifyDTO.getClientList()) {
					CustomerVerifyResultDTO customerVerifyResultDTO = new CustomerVerifyResultDTO();
					String bizNo = reqCustomerInfoDTO.getBizNo();
					String customerCode = resCustomerVerifyDTO.getClientList().get(0).getCustomerNo();
					String taxFlag = resCustomerVerifyDTO.getClientList().get(0).getTaxDiscountedExistIndi();
					EBResultCodeDTO eBResultCode = resCustomerVerifyDTO.getClientList().get(0).getResult();
					HXResultCodeDTO hxResultCode = new HXResultCodeDTO();
					hxResultCode.setResultCode(eBResultCode.getResultCode());
					String message = "";
					if(null != eBResultCode.getResultMessage()){
						StringBuffer sbStr = new StringBuffer(); 
						for(String mess : eBResultCode.getResultMessage()){
							sbStr.append(mess).append("|");
						}
						message = sbStr.substring(0, sbStr.length()-1).toString();
					}
					hxResultCode.setResultMessage(message);
					customerVerifyResultDTO.setBizNo(bizNo);
					customerVerifyResultDTO.setCustomerCode(customerCode);
					customerVerifyResultDTO.setTaxDiscountedExistIndi(taxFlag);
					customerVerifyResultDTO.setResult(hxResultCode);
					thirdSendResponse.setResJson(customerVerifyResultDTO);
					if(ENUM_RESULT_CODE.SUCCESS.code().equals(eBResultCode.getResultCode())){
						addCustomer(reqCustomerInfoDTO, customerCode, taxFlag);
					}	
				} else {
					BookSequenceDTO bookSequence = JSONObject.parseObject(responseBody.getJsonString(), BookSequenceDTO.class);
					TaxFaulTaskDTO taxFaultTask = new TaxFaulTaskDTO();
					taxFaultTask.setSerialNo(paramHead.getSerialNo());
					taxFaultTask.setServerPortCode(paramHead.getPortCode());
					taxFaultTask.setServerPortName(paramHead.getPortName());
					taxFaultTask.setAreaCode(paramHead.getAreaCode());
					taxFaultTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
					taxFaultTask.setBookSequenceNo(bookSequence.getBookingSequenceNo());
					faultTaskService.addTaxFaultTask(taxFaultTask);
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
				}
			}
		} catch (Exception e) {
			logger.error("客户验证上传失败："+e.getMessage());
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			// 存储任务表
			TaxFaulTaskDTO taxFaultTask = new TaxFaulTaskDTO();
			taxFaultTask.setServerPortCode(paramHead.getPortCode());
			taxFaultTask.setServerPortName(paramHead.getPortName());
			taxFaultTask.setAreaCode(paramHead.getAreaCode());
			taxFaultTask.setSerialNo(paramHead.getSerialNo());
			taxFaultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTaskService.addTaxFaultTask(taxFaultTask);
			e.printStackTrace();
		}
		logger.error("客户验证上传后置处理结束!");
		return thirdSendResponse;
	}
	/**
	 * 存储业务表数据
	 * @param reqCustomerInfoDTO
	 * @param customerCode
	 * @param taxFlag
	 */
	private void addCustomer(ReqCustomerInfoDTO reqCustomerInfoDTO, String customerCode, String taxFlag) {
		try {		
			TaxCustomer taxCustomer = new TaxCustomer();
			taxCustomer.setBizNo(reqCustomerInfoDTO.getBizNo());
			taxCustomer.setCustomerName(reqCustomerInfoDTO.getName());
			taxCustomer.setGender(reqCustomerInfoDTO.getGender());
			taxCustomer.setBirthday(DateUtil.parseDate(reqCustomerInfoDTO.getBirthday()));
			taxCustomer.setCardType(reqCustomerInfoDTO.getCertiType());
			taxCustomer.setCardNo(reqCustomerInfoDTO.getCertiNo());
			taxCustomer.setCustomerNo(customerCode);
			taxCustomer.setTaxFlag(taxFlag);
			taxCustomer.setRcState(ENUM_RC_STATE.EFFECTIVE.getCode());
			taxCustomer.setModifyDate(DateUtil.getCurrentDate());
			taxCustomer.setCreateDate(DateUtil.getCurrentDate());
			taxCustomer.setModifierId(SystemConstants.SYS_OPERATOR);
			taxCustomer.setCreatorId(SystemConstants.SYS_OPERATOR);
			taxCustomer.setNationality(CustomerConstants.CHINA);
			this.addCustomer(taxCustomer);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("客户验证上传数据持久化失败"+e.getMessage());
		}
	}
    /**
     * 核心DTO转换为中保信DTO（单笔）
     * @param customerInfoDTO
     * @return
     */
	public ReqCustomerVerifyDTO tansforDTO(ReqCustomerInfoDTO customerInfoDTO) {
		ReqCustomerVerifyDTO reqCustomerVerifyDTO=new ReqCustomerVerifyDTO();
		CustomerVerifyDTO customerDTO = new CustomerVerifyDTO();
		List<CustomerVerifyDTO> reqCustomerVerifyList = new ArrayList<CustomerVerifyDTO>();
		customerDTO.setBusiNo(customerInfoDTO.getBizNo());
		customerDTO.setName(customerInfoDTO.getName());
		customerDTO.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(), customerInfoDTO.getGender()));
		customerDTO.setBirthday(customerInfoDTO.getBirthday());
		customerDTO.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),customerInfoDTO.getCertiType()));
		customerDTO.setCertiNo(customerInfoDTO.getCertiNo());
		reqCustomerVerifyList.add(customerDTO);
		reqCustomerVerifyDTO.setClientList(reqCustomerVerifyList);
		return reqCustomerVerifyDTO;
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public ThirdSendResponseDTO addCustomers(List<ReqCustomerInfoDTO> reqcustomersDTO, ParamHeadDTO paramHead) {
		ThirdSendResponseDTO thirdSendResponse=new ThirdSendResponseDTO();
		try {
			logger.info("多笔客户验证上传（核心请求）JSON 体数据内容："+JSONObject.toJSONString(reqcustomersDTO));
			// 1.将客户验证请求dto转换为中保信客户验证请求dto
			ReqCustomerVerifyDTO  reqCustomerVerifyDTO = this.transforDTO(reqcustomersDTO);
			// 2.调用中保信接口服务,获得返回结果 存储调用中保信日志表
			ThirdSendDTO thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code(), paramHead,reqCustomerVerifyDTO);
			logger.info("多笔客户验证上传（请求中保信）JSON 数据内容："+JSONObject.toJSONString(thirdSendDTO));
			Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
			Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
			EbaoServerPortDTO ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code());
			String portUrl = ebaoServerPort.getPortUrl();
			URL wsdlLocation = new URL(portUrl);
			CustomerVerifyService_Service service = new CustomerVerifyService_Service(wsdlLocation);
			CustomerVerifyService servicePort = service.getCustomerVerifyServicePort();
			BindingProvider bp = (BindingProvider) servicePort;
			bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
			servicePort.verify(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
			ResponseHeader responseHeader = responseHeaderHolder.value;
			ResponseBody responseBody = responseBodyHolder.value;
			logger.info("多笔客户验证上传（中保信响应）JSON 数据内容："+responseBody.getJsonString());
			// 封装中保信返回报文
			ResponseJSON responseJSON = new ResponseJSON();
			responseJSON.setResponseBody(responseBody);
			responseJSON.setResponseHeader(responseHeader);
			// 封装发送报文日志对象
			SendLogDTO sendLog = new SendLogDTO();
			sendLog.setSerialNo(paramHead.getSerialNo());
			sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code());
			sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
			sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
			sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
			sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
			sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			commonCodeService.addLogSend(sendLog);
			// 3.封装返回核心dto;
			if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
					|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
			}else{
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				List list = responseHeader.getResultMessage().getMessage();
				if(list != null && list.size() > 0){
					StringBuffer sbStr = new StringBuffer(); 
					for(String mess : responseHeader.getResultMessage().getMessage()){
						sbStr.append(mess).append("|");
					}
					String message = sbStr.substring(0, sbStr.length()-1).toString();
					thirdSendResponse.setResultDesc(message);
				}else{
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				}
			}
			// 获取业务数据
			if(!StringUtil.isEmpty(responseBody.getJsonString())){
				ResCustomerVerifyDTO resCustomerVerifyDTO = JSONObject.parseObject(responseBody.getJsonString(), ResCustomerVerifyDTO.class);
				if (null != resCustomerVerifyDTO.getClientList()) {
					List<CustomerVerifyResultDTO> customerVerifyResultList=new ArrayList<CustomerVerifyResultDTO>();
					//遍历中保信返回的列表
					for (CustomerDTO customerDTO : resCustomerVerifyDTO.getClientList()) {
						for (ReqCustomerInfoDTO reqCustomerInfoDTO : reqcustomersDTO) {
							if(customerDTO.getBusiNo().equals(reqCustomerInfoDTO.getBizNo())){
								CustomerVerifyResultDTO customerVerifyResultDTO = new CustomerVerifyResultDTO();
								String bizNo = customerDTO.getBusiNo();
								String customerCode = customerDTO.getCustomerNo();
								String taxFlag = customerDTO.getTaxDiscountedExistIndi();
								EBResultCodeDTO eBResultCode = customerDTO.getResult();
								HXResultCodeDTO hxResultCode = new HXResultCodeDTO();
								hxResultCode.setResultCode(eBResultCode.getResultCode());
								String message = "";
								if(null != eBResultCode.getResultMessage())
								{
									StringBuffer sbStr = new StringBuffer(); 
									for(String mess : eBResultCode.getResultMessage()){
										sbStr.append(mess).append("|");
									}
									message = sbStr.substring(0, sbStr.length()-1).toString();
								}
								hxResultCode.setResultMessage(message);
								customerVerifyResultDTO.setBizNo(bizNo);
								customerVerifyResultDTO.setCustomerCode(customerCode);
								customerVerifyResultDTO.setTaxDiscountedExistIndi(taxFlag);
								customerVerifyResultDTO.setResult(hxResultCode);
								customerVerifyResultList.add(customerVerifyResultDTO);
								//存储业务表数据
								if(ENUM_RESULT_CODE.SUCCESS.code().equals(eBResultCode.getResultCode())){
									this.addCustomer(reqCustomerInfoDTO, customerCode, taxFlag);
								}
							}
						}
					}	
					thirdSendResponse.setResJson(customerVerifyResultList);
				}else{
					BookSequenceDTO bookSequence = JSONObject.parseObject(responseBody.getJsonString(), BookSequenceDTO.class);
					TaxFaulTaskDTO taxFaultTask = new TaxFaulTaskDTO();
					taxFaultTask.setSerialNo(paramHead.getSerialNo());
					taxFaultTask.setServerPortCode(paramHead.getPortCode());
					taxFaultTask.setServerPortName(paramHead.getPortName());
					taxFaultTask.setAreaCode(paramHead.getAreaCode());
					taxFaultTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
					taxFaultTask.setBookSequenceNo(bookSequence.getBookingSequenceNo());
					faultTaskService.addTaxFaultTask(taxFaultTask);
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
				}
			}
			    
		} catch (Exception e) {
			logger.error("多笔客户验证上传失败："+e.getMessage());
			thirdSendResponse.setResJson(e.getMessage());
			thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
			thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
			// 存储任务表
			TaxFaulTaskDTO taxFaultTask = new TaxFaulTaskDTO();
			taxFaultTask.setServerPortCode(paramHead.getPortCode());
			taxFaultTask.setServerPortName(paramHead.getPortName());
			taxFaultTask.setAreaCode(paramHead.getAreaCode());
			taxFaultTask.setSerialNo(paramHead.getSerialNo());
			taxFaultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
			faultTaskService.addTaxFaultTask(taxFaultTask);
			e.printStackTrace();
		}
		logger.error("多笔客户验证上传后置处理结束!");
		return thirdSendResponse;
	}
		
		/**
		 * 核心请求DTO转换为中保信DTO（多笔）
		 * @param customerInfoDTO
		 * @return
		 */
		public ReqCustomerVerifyDTO transforDTO(List<ReqCustomerInfoDTO> customerInfoDTO) {
			ReqCustomerVerifyDTO reqCustomerVerifyDTO=new ReqCustomerVerifyDTO();
			List<CustomerVerifyDTO> reqCustomerVerifyList = new ArrayList<CustomerVerifyDTO>();
			//遍历核心请求的客户验证列表（多笔）
			for(ReqCustomerInfoDTO reqCustomerInfoDTO : customerInfoDTO){
				CustomerVerifyDTO customerDTO = new CustomerVerifyDTO();
				customerDTO.setBusiNo(reqCustomerInfoDTO.getBizNo());
				customerDTO.setName(reqCustomerInfoDTO.getName());
				customerDTO.setGender(transCodeService.transCode(ENUUM_CODE_MAPPING.GENDER.code(), reqCustomerInfoDTO.getGender()));
				customerDTO.setBirthday(reqCustomerInfoDTO.getBirthday());
				customerDTO.setCertiType(transCodeService.transCode(ENUUM_CODE_MAPPING.CARDTYPE.code(),reqCustomerInfoDTO.getCertiType()));
				customerDTO.setCertiNo(reqCustomerInfoDTO.getCertiNo());
				reqCustomerVerifyList.add(customerDTO);
			}
			reqCustomerVerifyDTO.setClientList(reqCustomerVerifyList);
			return reqCustomerVerifyDTO;
		}
		
		@Override
		public TaxFaultTask customerExceptionJob(String reqJSON, String portCode, Integer faultTaskId) {
			logger.info("进入客户验证上传异常任务服务");
			ThirdSendResponseDTO thirdSendResponse = new ThirdSendResponseDTO();
			TaxFaultTask faultTask = taxFaultTaskMapper.selectByPrimaryKey(faultTaskId);
			try {
				ParamHeadDTO paramHead = new ParamHeadDTO();
				CoreRequestHead coreRequestHead = new CoreRequestHead();
				List<ReqCustomerInfoDTO> reqcustomersList = new ArrayList<ReqCustomerInfoDTO>();
				//1. 解析请求报文
				//单笔请求
				if (ENUM_HX_SERVICE_PORT_CODE.CUSTOMER_VERIFY_ONE.code().equals(portCode)) {
					ReqCustomerCoreDTO reqCustomerCore = JSONObject.parseObject(reqJSON, ReqCustomerCoreDTO.class);
					ReqCustomerInfoDTO reqCustomerInfoDTO = (ReqCustomerInfoDTO) reqCustomerCore.getBody();
					reqcustomersList.add(reqCustomerInfoDTO);
					coreRequestHead = reqCustomerCore.getRequestHead();
				//多笔请求	
				} else if (ENUM_HX_SERVICE_PORT_CODE.CUSTOMER_VERIFY_MORE.code().equals(portCode)){
					ReqCustomerMoreCoreDTO reqCustomerMoreCore = JSONObject.parseObject(reqJSON, ReqCustomerMoreCoreDTO.class);
					ReqCustomerMoreDTO reqCustomerMore = (ReqCustomerMoreDTO) reqCustomerMoreCore.getBody();
					reqcustomersList = reqCustomerMore.getClientList();
					coreRequestHead = reqCustomerMoreCore.getRequestHead();
				} else {
					throw new BusinessDataErrException("请求接口编码有误! 错误接口编码为："+portCode);
				}
				//2. 封装头部信息
				paramHead.setAreaCode(coreRequestHead.getAreaCode());
				paramHead.setRecordNum(coreRequestHead.getRecordNum());
				paramHead.setSerialNo(coreRequestHead.getSerialNo());
				paramHead.setPortCode(portCode);
				ThirdSendDTO thirdSendDTO = new ThirdSendDTO();
				EbaoServerPortDTO ebaoServerPort = null;
				
				Holder<ResponseHeader> responseHeaderHolder = new Holder<ResponseHeader>();
				Holder<ResponseBody> responseBodyHolder = new Holder<ResponseBody>();
				// 预约码处理方式
				if(ENUM_DISPOSE_TYPE.APPOINTMENT.code().equals(faultTask.getDisposeType())){
					//3. 封装请求中保信数据
					paramHead.setRecordNum("1"); //异步请求接口请求记录数为1
					BookSequenceDTO bookSequence = new BookSequenceDTO();
					bookSequence.setBookingSequenceNo(faultTask.getRemark());
					thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY_APPOINTMENT.code(), paramHead, bookSequence);
					ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ASYN_RESULT_QUERY.code());
					logger.info("预约码 - 客户验证上传（请求中保信）JSON 数据内容："+JSONObject.toJSONString(thirdSendDTO));
					//4. 调用统一的预约码查询接口地址
					String portUrl = ebaoServerPort.getPortUrl();
					URL wsdlLocation = new URL(portUrl);
					AsynResultQueryService_Service service = new AsynResultQueryService_Service(wsdlLocation);
					AsynResultQueryService servicePort = service.getAsynResultQueryServicePort();
					BindingProvider bp = (BindingProvider) servicePort;
					bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
					servicePort.asynResultQuery(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
					
				// 错误或异常处理方式	
				}else if(ENUM_DISPOSE_TYPE.ASYNC.code().equals(faultTask.getDisposeType()) || ENUM_DISPOSE_TYPE.ERROR.code().equals(faultTask.getDisposeType())){
					// 将续保信息上传请求dto转换为中保信续保信息上传请求dto
					ReqCustomerVerifyDTO reqCustomerVerifyDTO = this.transforDTO(reqcustomersList);
					thirdSendDTO = commonCodeService.createThirdSend(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code(), paramHead, reqCustomerVerifyDTO);
					ebaoServerPort = commonCodeService.queryEBaoServerInfoByPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code());
					logger.info("异常任务 - 客户验证上传（请求中保信）JSON 数据内容(错误或异常类型)："+JSONObject.toJSONString(thirdSendDTO));
					//4. 调用统一的预约码查询接口地址
					String portUrl = ebaoServerPort.getPortUrl();
					URL wsdlLocation = new URL(portUrl);
					CustomerVerifyService_Service service = new CustomerVerifyService_Service(wsdlLocation);
					CustomerVerifyService servicePort = service.getCustomerVerifyServicePort();
					BindingProvider bp = (BindingProvider) servicePort;
					bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, portUrl);
					servicePort.verify(thirdSendDTO.getHead(), thirdSendDTO.getBody(),responseHeaderHolder, responseBodyHolder);
				
				}else{
					throw new BusinessDataErrException("异常类型有误! 错误异常类型为："+ENUM_DISPOSE_TYPE.getEnumValueByKey(faultTask.getDisposeType()));
				}
				ResponseHeader responseHeader = responseHeaderHolder.value;
				ResponseBody responseBody = responseBodyHolder.value;
				logger.info("预约码/异常任务 - 客户验证上传（中保信响应）JSON 数据内容："+responseBody.getJsonString());
				ResponseJSON responseJSON = new ResponseJSON();
				responseJSON.setResponseBody(responseBody);
				responseJSON.setResponseHeader(responseHeader);
				// 如果是异步类型需要记录日志
				if(ENUM_DISPOSE_TYPE.ASYNC.code().equals(faultTask.getDisposeType())){
					SendLogDTO sendLog = new SendLogDTO();
					sendLog.setSerialNo(paramHead.getSerialNo());
					sendLog.setPortCode(ENUM_EBAO_SERVICE_PORT_CODE.ENUM_CUST_VERIFY.code());
					sendLog.setRequestContent(JSONObject.toJSONString(thirdSendDTO));
					sendLog.setResponseContent(JSONObject.toJSONString(responseJSON));
					sendLog.setTargetCode(ENUM_SENDSERVICE_CODE.EBAO.code());
					sendLog.setState(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
					sendLog.setDescription(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
					commonCodeService.addLogSend(sendLog);
				}
				// 初始化头部错误信息
				String messageBody = ENUM_BZ_RESPONSE_RESULT.FAIL.description();
				//5. 封装返回核心dto;
				if (ENUM_RESULT_CODE.SUCCESS.code().equals(responseHeader.getResultCode())
						|| ENUM_RESULT_CODE.INPUT_LOCALITY_SUCCESS.code().equals(responseHeader.getResultCode())) {
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.SUCCESS.description());
				}else if(ENUM_RESULT_CODE.REQ_AWAIT.code().equals(responseHeader.getResultCode())){
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
					thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
				}else{
					thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
					List list = responseHeader.getResultMessage().getMessage();
					if(list != null && list.size() > 0){
						StringBuffer sbStr = new StringBuffer(); 
						for(String mess : responseHeader.getResultMessage().getMessage()){
							sbStr.append(mess).append("|");
						}
						String message = messageBody = sbStr.substring(0, sbStr.length()-1).toString();
						thirdSendResponse.setResultDesc(message);
					}else{
						thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
					}
				}
				boolean isRegisterFaulTask = false;
				// 获取业务数据
				if(!StringUtil.isEmpty(responseBody.getJsonString())){
					ResCustomerVerifyDTO resCustomerVerifyDTO = JSONObject.parseObject(responseBody.getJsonString(), ResCustomerVerifyDTO.class);
					if (null != resCustomerVerifyDTO.getClientList()) {
						List<CustomerVerifyResultDTO> customerVerifyResultList=new ArrayList<CustomerVerifyResultDTO>();
						//遍历中保信返回的列表
						for (CustomerDTO customerDTO : resCustomerVerifyDTO.getClientList()) {
							for (ReqCustomerInfoDTO reqCustomerInfoDTO : reqcustomersList) {
								if(customerDTO.getBusiNo().equals(reqCustomerInfoDTO.getBizNo())){
									CustomerVerifyResultDTO customerVerifyResultDTO = new CustomerVerifyResultDTO();
									String bizNo =customerDTO.getBusiNo();
									String customerCode = customerDTO.getCustomerNo();
									String taxFlag = customerDTO.getTaxDiscountedExistIndi();
									EBResultCodeDTO eBResultCode = customerDTO.getResult();
									HXResultCodeDTO hxResultCode = new HXResultCodeDTO();
									hxResultCode.setResultCode(eBResultCode.getResultCode());
									String message = "";
									if(null != eBResultCode.getResultMessage())
									{
										StringBuffer sbStr = new StringBuffer(); 
										for(String mess : eBResultCode.getResultMessage()){
											sbStr.append(mess).append("|");
										}
										message = sbStr.substring(0, sbStr.length()-1).toString();
									}
									hxResultCode.setResultMessage(message);
									customerVerifyResultDTO.setBizNo(bizNo);
									customerVerifyResultDTO.setCustomerCode(customerCode);
									customerVerifyResultDTO.setTaxDiscountedExistIndi(taxFlag);
									customerVerifyResultDTO.setResult(hxResultCode);
									customerVerifyResultList.add(customerVerifyResultDTO);
									if(ENUM_RESULT_CODE.SUCCESS.code().equals(eBResultCode.getResultCode())){
										this.addCustomer(reqCustomerInfoDTO, customerCode, taxFlag);
									}
								}
							}
						}		
						thirdSendResponse.setResJson(customerVerifyResultList);
						isRegisterFaulTask = true;
					}else{
						BookSequenceDTO bookSequence = JSONObject.parseObject(responseBody.getJsonString(),BookSequenceDTO.class);
						// 插入异常任务表
						faultTask.setRemark(bookSequence.getBookingSequenceNo());
						faultTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
						thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.code());
						thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.EXCEPTION.description());
					}
				}else{
					thirdSendResponse.setResJson(messageBody);
				}
				if(isRegisterFaulTask){
					faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.SUCCESS.code());
				}else{
					faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				}
			} catch (Exception e) {
				logger.error("客户验证上传异常任务服务方法处理发生异常! 异常信息为："+e.getMessage());
				thirdSendResponse.setResJson(e.getMessage());
				thirdSendResponse.setResultCode(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				thirdSendResponse.setResultDesc(ENUM_BZ_RESPONSE_RESULT.FAIL.description());
				faultTask.setDisposeResult(ENUM_BZ_RESPONSE_RESULT.FAIL.code());
				if(ENUM_DISPOSE_TYPE.APPOINTMENT.code().equals(faultTask.getDisposeType())){
					faultTask.setDisposeType(ENUM_DISPOSE_TYPE.APPOINTMENT.code());
				}else{
					faultTask.setDisposeType(ENUM_DISPOSE_TYPE.ERROR.code());
				}
			} finally{
				faultTask.setSuccessMessage(JSONObject.toJSONString(thirdSendResponse));
				faultTask.setDisposeDate(DateUtil.getCurrentDate());
				taxFaultTaskMapper.updateByPrimaryKeySelective(faultTask);
			}
			logger.info("客户验证上传异常任务服务方法处理结束!");
			return faultTask;
		}
		
		/**
		 * 根据五要素查询客户是否存在
		 * @param taxCustomer
		 * @return
		 */
		private TaxCustomer queryCustomer(TaxCustomer taxCustomer){
			TaxCustomerExample example=new TaxCustomerExample();
			example.createCriteria().andRcStateEqualTo(ENUM_RC_STATE.EFFECTIVE.getCode())
			.andCustomerNameEqualTo(taxCustomer.getCustomerName()).andCardTypeEqualTo(taxCustomer.getCardType()).
			andGenderEqualTo(taxCustomer.getGender()).andCardNoEqualTo(taxCustomer.getCardNo()).andBirthdayEqualTo(taxCustomer.getBirthday());
			List<TaxCustomer>list=taxCustomerMapper.selectByExample(example);
			if(list!=null && list.size()>0){
				return list.get(0);
			}
			return null;
		}
		
		@Override
		public TaxCustomer addCustomer(TaxCustomer taxCustomer) {
			TaxCustomer temp=this.queryCustomer(taxCustomer);
			//客户不存在 添加新的客户
			if(temp == null){
				taxCustomerMapper.insert(taxCustomer);
				return taxCustomer;
			}
			return temp;
		}
		
		@Override
		public void addOrUpdateCustomer(TaxCustomer taxCustomer) {
			TaxCustomer temp=this.queryCustomer(taxCustomer);
			if(temp == null){
				taxCustomerMapper.insert(taxCustomer);
			}else{
				taxCustomer.setSid(temp.getSid());
				taxCustomerMapper.updateByPrimaryKeySelective(taxCustomer);
			}
		}
}